//
//  TitledPanel.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/4.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import SnapKit

protocol TitledPanelDelegate {
  func titledPanelButtonTapped(_ titledPanel: TitledPanel)
}

class TitledPanel: Panel {

  // MARK: - IBOutlets
  
  
  
  // MARK: - Private vars
  
  private let line = UIView()
  private let titleLabel = UILabel()
  private let button = UIButton(type: .system)
  
  // MARK: - Private methods
  
  @objc private func buttonTapped() {
    delegate?.titledPanelButtonTapped(self)
  }
  
  // MARK: - Public vars
  
  @IBInspectable var title: String = "--" {
    didSet {
      setup()
    }
  }
  
  @IBInspectable var buttonTitle: String = "" {
    didSet {
      setup()
    }
  }
  
  var delegate: TitledPanelDelegate?
  
  // MARK: - Lifecycle
  
  override func setup() {
    super.setup()
    
    line.backgroundColor = UIColor(fromRGB: 0x5D5D5D)
    addSubview(line)
    line.snp.makeConstraints { maker in
      maker.left.right.equalTo(self)
      maker.height.equalTo(1)
      maker.top.equalTo(self).offset(50)
    }
    
    titleLabel.text = title
    titleLabel.font = UIFont.systemFont(ofSize: 17)
    titleLabel.textColor = .white
    addSubview(titleLabel)
    titleLabel.snp.makeConstraints { maker in
      maker.leading.equalTo(15)
      maker.top.equalTo(15)
    }
    
    button.setTitle(buttonTitle, for: .normal)
    button.setTitleColor(UIColor(fromRGB: 0xFFFFFF), for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
    button.backgroundColor = UIColor(fromRGB: 0x747474)
    button.layer.cornerRadius = 4
    addSubview(button)
    button.snp.makeConstraints { maker in
      maker.top.equalTo(15)
      maker.trailing.equalTo(-15)
      maker.height.equalTo(20)
      maker.width.equalTo(50)
    }
    button.isHidden = (buttonTitle.trim().count == 0)
  }
  
  override var frame: CGRect {
    didSet {
      setup()
    }
  }
  
  override func layoutSubviews() {
    super.layoutSubviews()
    setup()
  }
  
  //  override public init(frame: CGRect) {
  //    super.init(frame: frame)
  //    setup()
  //  }
  //
  //  required public init?(coder aDecoder: NSCoder) {
  //    super.init(coder: aDecoder)
  //    setup()
  //  }
  
  override func awakeFromNib() {
    super.awakeFromNib()
    setup()
    
    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
  }
  
  override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    setup()
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  

}
